package ae.pcfc.cldos.online.common.manager.provider;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.io.CopyStreamException;
import org.springframework.integration.file.remote.session.Session;
import org.springframework.integration.file.remote.session.SessionFactory;

import ae.pcfc.cldos.online.common.manager.BaseManager;
import ae.pcfc.cldos.online.common.manager.FtpManager;

/**
 * 
 * @author arosa
 * 
 */
public class FtpManagerImpl extends BaseManager implements FtpManager {

	private SessionFactory<FTPFile> ftpSessionFactory;

	public void setFtpSessionFactory(SessionFactory<FTPFile> ftpSessionFactory) {
		this.ftpSessionFactory = ftpSessionFactory;
	}

	public InputStream getFile(final String fileLocation) throws FileNotFoundException {
		final Session<FTPFile> s = ftpSessionFactory.getSession();
		final PipedInputStream in = new PipedInputStream();
		try {
			
			final PipedOutputStream out = new PipedOutputStream(in);
			new Thread(new Runnable() {
				public void run() {
					try {
						s.read(fileLocation, out);
					} catch (CopyStreamException e){ 
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							out.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						s.close();
					}
				}
			}).start();

		} catch (IOException e) {
			e.printStackTrace();
			throw new FileNotFoundException();
		}
		return in;
	}

	public void writeFile(String fileLocation, InputStream is)
			throws IOException {
		Session<FTPFile> s = ftpSessionFactory.getSession();
		try{
			s.write(is, fileLocation);
		} finally{
			s.close();
		}
	}

	public void remove(String fileLocation) throws IOException {
		Session<FTPFile> s = ftpSessionFactory.getSession();
		try{
			s.remove(fileLocation);
		} finally{
			s.close();
		}
	}
	
	public boolean exist(String fileLocation) throws IOException{
		Session<FTPFile> s = ftpSessionFactory.getSession();
		boolean res = false;
		try{
			res = s.exists(fileLocation);
		} finally {
			s.close();
		}
		return res;		
	}
}
